package offerbook;

import java.util.PriorityQueue;
import java.util.Queue;

public class Code64_GetMedian1 {
    private Queue<Integer> smallQ = new PriorityQueue<>();
    private Queue<Integer> bigQ = new PriorityQueue<>((o1, o2)-> o2-o1);
    public void Insert(Integer num) {
        if(isEmpty()){
            bigQ.offer(num);
            return;
        }
        if(num > bigQ.peek()){
            smallQ.offer(num);
        }else{
            bigQ.offer(num);
        }
        adjust();

    }

    public Double GetMedian() {
        if(isEmpty()) return 0.0d;
        if(smallQ.size() == bigQ.size()){
            return ((double)(smallQ.peek() + bigQ.peek()))/2;
        }
        return smallQ.size() > bigQ.size() ? (double)smallQ.peek() : (double)bigQ.peek();
    }
    private void adjust(){
        if(Math.abs(smallQ.size() - bigQ.size()) > 1){
            if(smallQ.size() > bigQ.size()){
                bigQ.offer(smallQ.poll());
            }else{
                smallQ.offer(bigQ.poll());
            }
        }
    }
    private boolean isEmpty(){
        return smallQ.size() == 0 && bigQ.size() == 0;
    }


}